#! /usr/bin/env bash
#
# Build the semgrep-core statically-linked against musl, on alpine linux,
# with opam pre-installed.
#
# This script assumes we're at the root of the checked-out semgrep repository.
#
set -eu

# This is useful to locate 'dune' and for any build command not called
# by opam.
eval $(opam env)

# Sanity check
if [[ ! -e /etc/alpine-release ]]; then
  echo "Error: This doesn't look like an Alpine container." >&2
  exit 1
fi

# Avoid distracting warning in sudo 1.8.31
# 'sudo: setrlimit(RLIMIT_CORE): Operation not permitted'
echo "Set disable_coredump false" | sudo tee -a /etc/sudo.conf 2>/dev/null

# Obtain the sources if they're not here already. This is for local testing
# purposes, i.e. outside of GitHub Actions or CircleCI.
#
if [[ "$(basename "$(pwd)")" != semgrep ]]; then
  cd
  echo "Obtain semgrep sources"
  git clone https://github.com/returntocorp/semgrep.git
  cd semgrep
fi

echo "Install missing packages"
sudo apk add --no-cache perl m4

echo "Install submodules"
git submodule update --init --recursive

echo "Install ocaml-tree-sitter"
./install-scripts/install-ocaml-tree-sitter

echo "Install pfff"
opam install -y ./pfff

echo "Install semgrep-core"
(
  cd semgrep-core
  opam install --deps-only -y .
  make all
  make install
)

echo "Copy semgrep-core to artifacts"
mkdir -p artifacts
cp ./semgrep-core/_build/default/bin/Main.exe artifacts/semgrep-core
